package controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class DownloadController {
	
	@RequestMapping("/download")
	public void download(HttpServletResponse response,HttpSession session) throws Exception{
//		response.setHeader("content-disposition", "attachment;filename=ojdbc14.jar");
//		response.setHeader("content-disposition", "attachment;filename=a.jar");
		response.setHeader("content-disposition", new String("attachment;filename=啊.jar".getBytes("utf-8"),"iso8859-1"));
		
		
		ServletContext application=session.getServletContext();
		
		FileInputStream in=null;
		OutputStream out=null;
		
		try {
			in=new FileInputStream(application.getRealPath("file/ojdbc14.jar"));
			out=response.getOutputStream();
			
			byte[] b=new byte[2048];
			
			int n;
			
			while((n=in.read(b))!=-1){
				out.write(b,0,n);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	
	@RequestMapping("/download2")
	public ResponseEntity<byte[]> download2() throws Exception{
		HttpHeaders headers=new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", "ojdbc14.jar");
		
		File file=new ClassPathResource("ojdbc14.jar").getFile();

		System.out.println(file.getCanonicalPath());

		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
										  headers,
										  HttpStatus.OK);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	

}
